package com.zetyun.tiger.format.charset;

import com.zetyun.rt.sdk.action.MapAction;
import com.zetyun.rt.sdk.model.RtEvent;
import com.zetyun.rt.sdk.operator.OperatorContext;

import java.nio.charset.StandardCharsets;

//@ActionMeta(
//        id = "tiger.transform-charset",
//        tags = {"transform"},
//        category = "map",
//        name = "CharsetTransformAction",
//        parameterClass = CharsetTransformParameter.class,
//        status = ActionMeta.Status.PUBLIC,
//        description = "转换字段编码\n" +
//                "参考自：https://blog.csdn.net/weixin_43641651/article/details/85265550"
//)
public class CharsetTransformAction extends MapAction {


    private String fieldName;
    private CharsetTransformParameter parameter;


    @Override
    public void init(OperatorContext context) {
        super.init(context);
        parameter = context.getParameters();
        fieldName = parameter.getFieldName();
    }

    @Override
    public RtEvent apply(RtEvent rtEvent) throws Exception {

        String field = rtEvent.getField(fieldName, String.class);
        if (!field.isEmpty()) {
            String transformValue = getUTF8StringFromGBKString(field);
            rtEvent.setField(fieldName, transformValue);
        }
        return rtEvent;
    }


    public String getUTF8StringFromGBKString(String gbkStr) {
        return new String(getUTF8BytesFromGBKString(gbkStr), StandardCharsets.UTF_8);
    }

    public byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }

}
